package com.zm.zmgz.controller;

import com.zm.zmgz.pojo.Response;
import com.zm.zmgz.utils.ConfigureBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: cjw
 * @Date: 2020/06/10/18:53
 * @Description:通用的controller层
 */
@RestController
@RequestMapping("/generalContrlloer")
public class GeneralContrlloer {

    @Autowired
    ConfigureBean configureBean; // 获取配置文件自定义属性

    /***
     * @Description:
     * @Param: file为接收的文件;name为文件名(可以为空)
     * @return: 将上传的文件保存到服务器(按照年, 月, 日, 类型分好文件夹)
     * @Author: cjw
     * @Date: 2020-06-10 18:55:01
     */
    @PostMapping("/upfile")
    public Response upfile(@RequestParam MultipartFile file, @RequestParam String name, HttpServletRequest request) {
//        旧文件名
        String oldname = "";
        if (Objects.isNull(name)) {
            oldname = file.getOriginalFilename();
        } else {
            oldname = name;
        }
        System.out.println("旧名字:" + oldname);
        // 32位uuid+尾缀
        String newname = UUID.randomUUID().toString() + oldname.substring(oldname.lastIndexOf("."));
        System.out.println("新文件名:" + newname);
//        文件目录
        String filepath = request.getServletContext().getRealPath("/" + oldname.substring(oldname.lastIndexOf(".") + 1));
        SimpleDateFormat format = new SimpleDateFormat("/yyyy/MM/dd/");
        String date = format.format(new Date());
        filepath += date;
        System.out.println("存储路径:" + filepath);
//        创建新文件
        File newfile = new File(filepath + newname);
        if (!newfile.exists()) {
            newfile.mkdirs();
        }
        System.out.println("新文件:" + newfile.getAbsolutePath());
//        保存文件
        try {
            file.transferTo(newfile);
//            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/img" + date + newname;
            String url = request.getScheme() + "://" + configureBean.getServerAddress() + ":" + configureBean.getServerPort() + "/img" + date + newname;
            System.out.println("url:" + url);
            return new Response(20000, "图片上传成功!", url);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        返回url
        return new Response(20000, "图片上传失败!", null);
    }


}
